/******************** (C) COPYRIGHT 2018 merafour ********************
* Author             : 冷月追风@merafour.blog.163.com
* Version            : V1.0.0
* Date               : 12/1/2019
* Description        : 数据格式转换,需根据数据的存储格式相应调整代码.
********************************************************************************
* merafour.blog.163.com
* merafour@163.com
* github.com/Merafour
*******************************************************************************/
#include "cjsonformat.h"

cJSONformat::cJSONformat()
{

}

int cJSONformat::format_cutover(const char *open_path, const char *save_path)
{
    cJSON *root=nullptr;
    char* json_str=nullptr;
    char* imagebyte=nullptr;
    imagebyte = open(open_path);
    if(nullptr==imagebyte)
    {
        return -1;
    }

    root = format_decode(imagebyte);
    if(nullptr==root) return -1;
    json_str = cJSON_Print(root);
    //qDebug("root: %s", json_str);
    if(0!=save(save_path, json_str))
    {
        free(json_str);
        return -1;
    }
    free(json_str);
    return 0;
}

cJSON *cJSONformat::format_decode(const char *imagebyte)
{
    const char search_str[] = "\"item\":";
    cJSON* root=nullptr;
    cJSON* item=nullptr;
    //char* json_str=nullptr;
    const char *image_next=nullptr;
    //const char *image_new=nullptr;
    const char *image_new_line=nullptr;
    //uint32_t image_size=0;
    uint32_t count=0;

    root = cJSON_Parse(imagebyte);
    if(nullptr == root)
    {
        qDebug("Parse JSON fail");
        return nullptr;
    }
    //image_size = static_cast<uint32_t>(strlen(imagebyte));
    image_next = imagebyte;
    // search str
    while(1)
    {
        image_new_line = strstr(image_next, search_str);
        if(nullptr==image_new_line) goto bad;
        //qDebug("data: %s", image_new);
        image_next = image_new_line+strlen(search_str);
        //qDebug("\n\nimage_next: %s", image_next);

        item = cJSON_Parse(image_next);
        if(nullptr!=item)
        {
            cJSON_Delete(item);
            item=nullptr;
            break;
        }
    }
    // decode
    while(1)
    {
        // 从新行匹配字符串
        image_next = image_new_line;
        image_new_line = strstr(image_next, search_str);
        if(nullptr==image_new_line) break;
        // 取出 cJSON
        image_next = image_new_line+strlen(search_str);
        item = cJSON_Parse(image_next);
        // 换行
        image_new_line = strchr(image_next, '\n');
        if(nullptr==image_new_line) break;
        if(nullptr==item)
        {
            continue;
        }
        cJSON_AddItemToObject(root, "item", item);
//        json_str = cJSON_Print(item);
//        //json_str = cJSON_PrintUnformatted(root);
//        qDebug("json[%d]: %s", count, json_str);
//        free(json_str);
        //json_str=nullptr;
        //qDebug("image_new: %s", image_new);
        count++;
    }
    return root;
bad:
    cJSON_Delete(root);
    return nullptr;
}
